<template>
  <div class="firmware">
    <div class="firmware-top">
      <el-button
        type="primary"
        plain
        icon="el-icon-plus"
        size="mini"
        @click="handleAuthorization"
        >生成授权</el-button
      >
    </div>
    <el-table :data="authorizationList">
      <el-table-column label="序列号" sortable align="center" prop="deviceId" />
      <el-table-column label="状态" align="center" prop="use_state">
        <template slot-scope="scope">
          <el-tag type="danger" v-if="scope.row.use_state == 'FALSE'">未使用</el-tag>
          <el-tag type="success" v-else>已使用</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="激活时间" sortable align="center" prop="useTime" />
      <el-table-column label="创建时间" sortable align="center" prop="createTime" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button size="mini" type="text" @click="handleDelete(scope.row)"
            >删除</el-button
          >
        </template>
      </el-table-column>
    </el-table>
    <pagination
      v-show="total > 0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getAuhorizationList"
    />
    <authorization-dialog :open="open" @cancel="cancel" :id="id" />
  </div>
</template>

<script>
import authorizationDialog from "./authorization-dialog";
import { codeList, delAuthCode } from "@/api/login";

export default {
  props: {
    id: {
      type: [Number, String],
      default: "",
    },
  },
  data() {
    return {
      open: false,
      authorizationList: [],
      queryParams: {
        pageSize: 10,
        pageNum: 1,
      },
      total: 0,
    };
  },
  components: {
    authorizationDialog,
  },
  methods: {
    async getAuhorizationList() {
      try {
        const {
          id,
          queryParams: { pageSize, pageNum },
        } = this;
        const {
          data: { list, total },
        } = await codeList(id, pageSize, pageNum);
        this.authorizationList = list || [];
        this.total = total;
      } catch (error) {
        console.error("获取固件管理列表失败", error);
      }
    },
    async handleDelete(row) {
      const { codeId } = row;
      try {
        const flag = await this.$modal.confirm("是否确认删除该数据项？");
        if (!flag) return;
        await delAuthCode(codeId);
        this.getAuhorizationList();
        this.$modal.msgSuccess("操作成功");
      } catch (error) {
        console.error("操作失败", error);
      }
    },
    cancel() {
      this.open = false;
    },
    handleAuthorization() {
      this.open = true;
    },
  },
  created() {
    this.getAuhorizationList();
  },
};
</script>

<style scoped lang="scss">
.firmware {
  margin: 0 0 22px 0;
  .firmware-top {
    margin-bottom: 22px;
    display: flex;
    align-items: center;
    justify-content: flex-end;
  }
}
</style>
